<!-- 角色编辑弹窗 -->
<template>
  <div><el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '修改服务' : '添加服务' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <el-form ref="formName"
                   :model="form"
                   label-width="100px"
                   :rules="rules">
            <el-form-item label="商品名称:"
                          prop="tradeName">
              <el-input clearable
                        :maxlength="100"
                        v-model="form.tradeName"
                        placeholder="请输入分类名称">
              </el-input>
            </el-form-item>
            <el-form-item label="服务价格:"
                          prop="servicePrice">
              <el-input clearable
                        min="0"
                        type="number"
                        :maxlength="100"
                        v-model.number="form.servicePrice"
                        placeholder="请输入服务价格">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="服务原价:"
                          prop="originalServicePrice">
              <el-input clearable
                        min="0"
                        type="number"
                        :maxlength="100"
                        v-model.number="form.originalServicePrice"
                        placeholder="请输入服务原价">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="服务时间:"
                          prop="serviceTime">
              <el-input clearable
                        :maxlength="100"
                        min="0"
                        type="number"
                        v-model="form.serviceTime"
                        placeholder="请输入服务时间/分钟">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>
            <el-form-item label="加钟价格:"
                          prop="plusClockPrice">
              <el-input clearable
                        :maxlength="100"
                        min="0"
                        type="number"
                        v-model.number="form.plusClockPrice"
                        placeholder="请输入加钟价格">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="加钟折扣:"
                          prop="clockDiscount">
              <el-input clearable
                        min="0"
                        max="100"
                        type="number"
                        v-model="form.clockDiscount"
                        placeholder="请输入加钟折扣">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="加钟时长:"
                          label-width="100px"
                          prop="clockTime">
              <el-input clearable
                        :maxlength="100"
                        v-model.number="form.clockTime"
                        placeholder="请输入加钟时长/分钟">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>

            <el-form-item label="虚拟销量:"
                          label-width="100px"
                          prop="virtualSales">
              <el-input clearable
                        min="0"
                        type="number"
                        :maxlength="100"
                        v-model="form.virtualSales"
                        placeholder="请输入虚拟销量">
                <template slot="append">数量</template>
              </el-input>
            </el-form-item>
            <el-form-item label="抵扣积分:"
                          prop="maxDeductionPoints">
              <el-input clearable
                        :maxlength="100"
                        min="0"
                        type="number"
                        v-model="form.maxDeductionPoints"
                        placeholder="请输入最多抵扣多少积分”">
              </el-input>
            </el-form-item>
            <el-form-item label="赠送积分:"
                          prop="orderPoints">
              <el-input clearable
                        min="0"
                        type="number"
                        :maxlength="100"
                        v-model="form.orderPoints"
                        placeholder="请输入下单送多少积分”">
              </el-input>
            </el-form-item>

            <el-form-item label="是否推荐:"
                          prop="recommendedNot">
              <el-radio-group v-model="form.recommendedNot">
                <el-radio :label="2"
                          :value="2">否</el-radio>
                <el-radio :label="1"
                          :value="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否上架:"
                          prop="notGrounding">
              <el-radio-group v-model="form.notGrounding">
                <el-radio :label="2"
                          :value="2">否</el-radio>
                <el-radio :label="1"
                          :value="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 提交图片 -->
            <el-form-item label="所属分类:"
                          prop="serviceCategoriesId">
              <el-select clearable
                         class="ele-block"
                         v-loadmore="loadMoreAgent"
                         v-model="form.serviceCategoriesId"
                         @visible-change="(event) => getCategoriesList(event)"
                         placeholder="请选择所属分类">
                <el-option v-for="(item, index) in serviceCategoriesList"
                           :key="index"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传图片:"
                          prop="rotationChart">
              <el-upload action="#"
                         :on-exceed="exceedFn"
                         list-type="picture-card"
                         :file-list="fileList"
                         :limit="1"
                         :on-change="
                  (files, fileList) => handleFileChange(files, fileList)
                "
                         :auto-upload="false">
                <i slot="default"
                   class="el-icon-plus"></i>
                <div slot="file"
                     slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail"
                       :src="file.url"
                       alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview()">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete"
                          @click="handleDownload(file)">
                      <i class="el-icon-download"></i>
                    </span>
                    <span class="el-upload-list__item-delete"
                          @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
            </el-form-item>

            <el-form-item label="服务简介:"
                          label-width="100px"
                          prop="label">
              <el-tag :key="tag"
                      v-for="tag in dynamicTags"
                      closable
                      :disable-transitions="false"
                      @close="handleCloseTag(tag)">
                {{tag}}
              </el-tag>
              <el-input class="input-new-tag"
                        v-if="inputVisible"
                        v-model="inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm">
              </el-input>
              <el-button v-else
                         class="button-new-tag"
                         size="small"
                         @click="showInput">+ 服务简介</el-button>

            </el-form-item>
            <el-form-item label="服务详情:"
                          prop="serviceDetails">
              <tinymce-editor v-model="form.serviceDetails"
                              :init="editorConfig" />
            </el-form-item>
          </el-form>
          <div class="drawer__footer">
            <el-button round
                       type="plain"
                       @click="handleClose"
                       size="medium">返回</el-button>
            <el-button type="primary"
                       round
                       size="medium"
                       @click="save"
                       :loading="loading">提交</el-button>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import { getToken } from '@/utils/token-util';
import {
  userOssSignature,
  qnyOssSignature
} from '@/api/creatCenter/material';
// 要引入组件
import { storageConfigDetail } from '@/api/storageInfo/index';
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import axios from 'axios';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import {
  siteServiceInsert,
  siteServiceModify,
  siteServiceDetail
} from '@/api/serviceManagement/serviceList';
import { siteCategoriesList } from '@/api/serviceManagement/categoriesList';
export default {
  name: 'pictureEdit',
  components: { TinymceEditor, ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const rotationChart = (rule, value, callback) => {
      if (!this.form.rotationChart) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 商品名称
      tradeName: '',
      // 所属分类”
      serviceCategoriesId: '',
      //服务价格
      servicePrice: '',
      // 服务原价
      originalServicePrice: '',
      // 服务时间/分钟
      serviceTime: '',
      // 加钟价格
      plusClockPrice: '',
      //加钟折扣
      clockDiscount: '',
      //加钟时长/分钟
      clockTime: '',
      //   虚拟销量
      virtualSales: '',
      // 是否推荐 1.是 2.否”
      recommendedNot: 2,
      //是否上架 1.是 2.否”
      notGrounding: 2,
      //  最多抵扣多少积分
      maxDeductionPoints: '',
      //   标签
      label: '',
      // 下单送多少积分
      orderPoints: '',
      // 轮播图
      rotationChart: '',
      // 服务详情
      serviceDetails: '',
      // 站点id
      siteId: this.$store.state.site.info.id,
      pageNum: 1,
      count: 0
    };
    return {
      options: [],
      imageUrl: '',
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        tradeName: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        serviceCategoriesId: [
          {
            required: true,
            message: '请输入所属分类',
            trigger: 'blur'
          }
        ],
        originalServicePrice: [
          {
            required: true,
            message: '请输入服务价格',
            trigger: 'blur'
          }
        ],
        serviceTime: [
          {
            required: true,
            message: '请输入服务时间',
            trigger: 'blur'
          }
        ],
        plusClockPrice: [
          {
            required: true,
            message: '请输入加钟价格',
            trigger: 'blur'
          }
        ],
        servicePrice: [
          {
            required: true,
            message: '请输入服务价格',
            trigger: 'blur'
          }
        ],
        clockDiscount: [
          {
            required: true,
            message: '请输入加钟折扣',
            trigger: 'blur'
          }
        ],
        recommendedNot: [
          {
            required: true,
            message: '请填写是否推荐',
            trigger: 'blur'
          }
        ],
        notGrounding: [
          {
            required: true,
            message: '请填写是否上架',
            trigger: 'blur'
          }
        ],
        maxDeductionPoints: [
          {
            required: true,
            message: '请输入最多折扣多少',
            trigger: 'blur'
          }
        ],
        orderPoints: [
          {
            required: true,
            message: '请输入下单送多少积分',
            trigger: 'blur'
          }
        ],
        serviceDetails: [
          {
            required: true,
            message: '请输入服务详情',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        rotationChart: [
          { required: true, validator: rotationChart, trigger: 'change' }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false,
      canRun: false,
      imgViewArr: [],
      serviceCategoriesList: [],
      storageMode: '',
      inputVisible: false,
      inputValue: '',
      dynamicTags: [],
      editorConfig: {
        height: 525,
        relative_urls: false,
        convert_urls: false,


        images_upload_handler: async (blobInfo, success, error) => {
          console.log(this.storageModeFn())

          if (this.storageModeFn() == 2) {

            const results = await userOssSignature();
            const files = blobInfo.blob();
            console.log(files)
            // let files = files.raw;
            let filename = files.name;
            let markIndex = filename.lastIndexOf('.');
            let suffix = filename.substring(markIndex);
            let date = new Date().getTime();
            // // 构建请求参数
            let param = new FormData();
            param.append('key', date + suffix);
            param.append('policy', results.policy);
            param.append('OSSAccessKeyId', results.accessId);
            param.append('success_action_status', '200');

            param.append('signature', results.signature);
            param.append('file', files, files.name);
            param.append('success_action_status', '200');
            let config = {
              headers: {
                'Access-Control-Allow-Origin': '*',
                'x-oss-callback-Authorization': getToken()
              }
            };
            console.log('suffix', suffix);

            let result = await axios.post(results.host, param, config);
            let url = results.host + '/' + date + suffix;
            console.log(url);


            success(url)

          } else if (this.storageModeFn() == 3) {
            //  ==================================

            const files = blobInfo.blob();
            // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
            const param = new FormData();

            param.append('file', files, files.name);
            param.append('getsize', files.size);
            param.append('getContentType', files.type);
            param.append('getoriginalfilename', files.name);
            param.append('getName', files.name);

            const res = await qnyOssSignature(param);
            console.log(res.url);

            success(res.url)
          }






          // request({
          //   url: '/common/uploadFile',
          //   method: 'post',
          //   data: formData,
          //   onUploadProgress: (e) => {  // 文件上传进度回调

          //   }
          // }).then((res) => {
          //   if (res.data.code === 0) {
          //     success(res.data.data.url);
          //   } else {
          //     error(res.data.message);
          //   }
          // }).catch((e) => {
          //   error('exception');
          // });
        }
      },
    };
  },
  created () {
    this.storageConfig();
  },
  methods: {
    storageModeFn () {
      return this.storageMode
    },
    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    handleCloseTag (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      if (this.dynamicTags.length == 1) {
        this.form.label = this.dynamicTags[0]
      } else {
        this.form.label = this.dynamicTags.join(',')
      }
    },
    showInput () {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm () {
      console.log('=====================================')
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      if (this.dynamicTags.length == 1) {
        this.form.label = this.dynamicTags[0]
      } else {
        this.form.label = this.dynamicTags.join(',')
      }

      this.inputVisible = false;
      this.inputValue = '';
    },

    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 获取存储配置
    async storageConfig () {
      const res = await storageConfigDetail();

      //   console.log(res.storageMode);

      this.storageMode = res?.storageMode;
    },
    async task () {
      if (this.count > 10) {
        //页数加一
        this.pageNum++;
        // //发送网络请求
        console.log(this.pageNum);

        const res = await siteCategoriesList({
          limit: 10,

          page: this.pageNum,
          siteId: this.$store.state.site.info.id
        });

        console.log(res);
        this.count = res.data.count;

        const agentList = res.data.list.map((item) => {
          return {
            label: item.classificationName,
            value: item.id
          };
        });
        this.serviceCategoriesList =
          this.serviceCategoriesList.concat(agentList);
        console.log(this.serviceCategoriesList);

        this.count = this.count - 10;
      }
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file, fileList) {
      if (this.storageMode == 2) {
        this.aliFn(file, fileList);
      } else if (this.storageMode == 3) {
        this.qnyFn(file, fileList);
      }
    },

    // 阿里云
    async aliFn (file, fileList) {
      this.loading = true;
      const res = await userOssSignature();
      let files = file.raw;
      let filename = file.name;
      let markIndex = filename.lastIndexOf('.');
      let suffix = filename.substring(markIndex);
      let date = new Date().getTime();
      // 构建请求参数
      let param = new FormData();
      param.append('key', date + suffix);
      param.append('policy', res.policy);
      param.append('OSSAccessKeyId', res.accessId);
      param.append('success_action_status', '200');
      // param.append("callback",  this.data.callback)     //回调（not)
      param.append('signature', res.signature);
      param.append('file', files, files.name);
      param.append('success_action_status', '200');
      let config = {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'x-oss-callback-Authorization': getToken()
        }
      };
      console.log('suffix', suffix);

      let result = await axios.post(res.host, param, config);
      let url = res.host + '/' + date + suffix;
      console.log(url);
      this.form.rotationChart = url;
      this.imageUrl = url;
      this.loading = false;
    },
    async qnyFn (file, fileList) {
      this.loading = true;
      console.log(file, fileList);

      let files = file.raw;
      console.log(files);
      //   // 构建请求参数
      let param = new FormData();

      param.append('file', files, files.name);
      param.append('getsize', files.size);
      param.append('getContentType', files.type);
      param.append('getoriginalfilename', files.name);
      param.append('getName', files.name);

      const res = await qnyOssSignature(param);
      console.log(res.url);
      this.imageUrl = res.url;
      this.form.rotationChart = res.url;
      console.log('上传图片成功=======', res);
      this.loading = false;
    },
    loadMoreAgent () {
      this.throttle(this.task, 1000)();
    },
    throttle (fun, timeout) {
      this.canRun = true;
      return () => {
        // 如果是true 就不走这
        if (!this.canRun) return;
        this.canRun = false;
        setTimeout(() => {
          fun();
          this.canRun = true;
        }, timeout);
      };
    },

    async getCategoriesList (val) {
      if (val) {
        console.log(val);
        const res = await siteCategoriesList({
          limit: 10,
          page: this.pageNum,
          siteId: this.$store.state.site.info.id
        });

        const agentList = res.list.map((item) => {
          return {
            label: item.classificationName,
            value: item.id
          };
        });
        console.log(agentList);
        this.serviceCategoriesList = agentList;
      }
    },
    /* 保存编辑 */
    save () {
      this.$refs['formName'].validate((valid) => {
        if (!valid) {
          return false;
        }
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;
        data.rotationChart = this.imageUrl;
        const saveOrUpdate = this.isUpdate
          ? siteServiceModify
          : siteServiceInsert;

        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg);
            if (!this.isUpdate) {
              this.$router.go(0);
            }
            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(async () => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.id = '';
            const imgStr = this.data.label
            if (imgStr?.length) {
              if (imgStr.includes(',')) {
                console.log('字符串中包含逗号');
                // 包含的进行slice(',') 分割
                this.dynamicTags = imgStr.split(',').map((item) => item.trim());
              } else {
                console.log('字符串中不包含逗号');
                this.dynamicTags = imgStr.split();
              }


            }
            this.$util.assignObject(this.form, {
              ...this.data
            });

            if (this.data.serviceCategoriesId) {
              console.log(this.data.serviceCategoriesId);
              const res = await siteCategoriesList({
                limit: 10,
                page: 1,
                siteId: this.$store.state.site.info.id
              });
              const agentList = res.list.map((item) => {
                return {
                  label: item.classificationName,
                  value: item.id
                };
              });
              console.log(agentList);
              this.serviceCategoriesList = agentList;
            }

            if (this.form.rotationChart) {
              this.imageUrl = this.form.rotationChart;
              let markIndex = this.form.rotationChart.lastIndexOf('.');
              let suffix = this.form.rotationChart.substring(markIndex);

              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.rotationChart
                });
              } else {
                this.fileList = [
                  {
                    name: suffix,
                    url: this.form.rotationChart
                  }
                ];
              }
            } else {
              this.fileList = [];
            }

            this.isUpdate = true;
          } else {
            this.isUpdate = false;
            this.dynamicTags = []
          }
        } else {
          this.$nextTick(() => {
            this.$refs['formName'].resetFields();
            console.log(this.form);
          });
          this.dynamicTags = []
          this.fileList = [];
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .el-button--small {
  margin-left: 5px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 100px;
}
</style>
